import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {HttpClient} from '@angular/common/http';
import {NzImageService} from 'ng-zorro-antd/image';
import {moveItemInArray} from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-image-upload',
  templateUrl: './image-upload.component.html',
  styleUrls: ['./image-upload.component.scss']
})
export class ImageUploadComponent implements OnInit {
  @Input() imageUrls: string[] = []; // 多图
  @Input() imageUrl = ''; // 单图
  @Input() deleteBtnVisible = true; // 图片删除按钮显隐
  @Input() addFileArea = true; // 选择文件显隐
  @Input() mainImgBtn = false; // 设为主图按钮显示
  @Input() dragDisabled = true; // 拖动是否禁用
  @Input() maxImgLength = 8; // 图片最大数量
  @Input() maxWidth = '440px'; // 组件最大宽度
  @Output() setMainImg = new EventEmitter(); // 设为主图事件
  @Output() deleteImg = new EventEmitter(); // 删除图片事件
  @Output() urlChange = new EventEmitter(); // 图片改变事件
  @Input() isUsedCommodity = false; // 是否是二手商品的图片上传，是的话要单独处理
  constructor(
    private message: NzMessageService,
    private httpClient: HttpClient,
    private nzImageService: NzImageService,
  ) {
  }

  ngOnInit(): void {
  }

  // 图片改变
  async fileChange(event: any) {
    console.log(event.target.files);
    for (let i = 0; i < event.target.files.length; i++) {
      if (this.imageUrls.length >= this.maxImgLength) {
        this.message.error(`最多只能添加${this.maxImgLength}张`);
        break;
      }
      await this.uploadImg(event.target.files[i]).then(url => {
        this.urlChange.emit(url);
      }).catch(err => {
        this.message.error(err);
      });
    }
    event.target.files = null;
  }

  // 上传图片
  uploadImg(img: any) {
    const file = new FormData();
    file.append('file', img);
    file.append('name', this.isUsedCommodity ? 'green' : (+new Date()).toString());
    return new Promise((resolve, reject) => {
      this.httpClient.post(this.isUsedCommodity ? '/common/upload/zoomImg' : '/common/upload/file', file).toPromise().then((res: any) => {
        if (res.code === 0) {
          resolve(res.data);
        } else {
          reject(res.message);
        }
      }).catch(() => {
        reject('图片上传异常');
      });
    });
  }

  // 查看图片
  previewImage(src: string) {
    this.nzImageService.preview([{src, height: '400px'}], {nzZoom: 1.5, nzRotate: 0});
  }

  // 删除图片
  removeOptionImage(index: any) {
    this.deleteImg.emit(index);
  }

  // 设为主图
  setMainImgClick(index: any) {
    this.setMainImg.emit(index);
  }

  // 拖拽选项
  dropOption(event: any) {
    moveItemInArray(this.imageUrls, event.previousIndex, event.currentIndex);
  }

}
